#pragma once
#include <iostream>
#include <string>
#include <pthread.h>
#include <functional>

namespace ns_thread
{
    using func_t = std::function<void(std::string)>;
    class Thread
    {
    private:
        void Excute()
        {
            _func(_name);
        }

    public:
        Thread(func_t func, std::string who = "None name")
            : _name(who), _func(func), _isrunning(false)
        {
        }

        static void *threadrun(void *args)
        {
            Thread *self = (Thread *)args;
            self->Excute();
            return nullptr;
        }
        bool start()
        {
            int n = pthread_create(&_tid, nullptr, threadrun, this);
            if (n == 0)
            {
                _isrunning = true;
                return true;
            }
            else
            {
                return false;
            }
        }

        void Join()
        {
            if (_isrunning == true)
                pthread_join(_tid, nullptr);
        }
        std::string name()
        {
            return _name;
        }
        void Detach()
        {
            if (_isrunning == true)
                pthread_detach(_tid);
        }

        void Stop()
        {
            _isrunning = false;
        }
        ~Thread()
        {
        }

    private:
        pthread_t _tid;
        std::string _name;
        func_t _func;
        bool _isrunning;
    };
}